package com.project.lk.nurseapp.babyvoice;

import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.project.lk.nurseapp.R;
import com.project.lk.nurseapp.base.BaseActivity;
import com.project.lk.nurseapp.common.view.bluetooth.BleManager;
import com.project.lk.nurseapp.common.view.bluetooth.BluetoothListActivity;
import com.project.lk.nurseapp.common.view.bluetooth.StarConstants;
import com.project.lk.nurseapp.common.view.chat.voice.MediaPlayerManager;
import com.project.lk.nurseapp.utils.AppManager;
import com.project.lk.nurseapp.utils.ByteToStringUtils;
import com.project.lk.nurseapp.utils.MediaUtils;
import com.project.lk.nurseapp.utils.PopWindowManager;
import com.project.lk.nurseapp.utils.SharedPreferencesUtils;
import com.project.lk.nurseapp.utils.TimeUtils;
import com.project.lk.nurseapp.utils.ToastUtils;
import com.suke.widget.SwitchButton;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.project.lk.nurseapp.common.view.bluetooth.StarConstants.sphy_code_begin;
/**
 * 功能介绍：
 * 项目名：
 * 模块名称：
 * 作者：LK
 * 日期：2018/1/9
 * 修改日期：
 */
public class BabyVoiceActivity extends BaseActivity {


    @BindView(R.id.hint_tv)
    TextView hintTv;
    BleManager bleManager;
    @BindView(R.id.time_tv)
    TextView timeTv;
    @BindView(R.id.voice_chart)
    LineChart voiceChart;
    @BindView(R.id.item_time)
    TextView itemTime;
    @BindView(R.id.item_voice_layout)
    LinearLayout itemVoiceLayout;
    @BindView(R.id.voice_tv)
    TextView voiceTv;
    @BindView(R.id.switch_button)
    SwitchButton switchButton;
    SoundCard mSoundCard;
    private AudioManager audiomanage;

    @Override
    protected void initData() {
        YData.add((float) 0);
        setLineChart();
        timeTv.setText(TimeUtils.getSateTime(new Date()));
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    protected void initView() {
        bleManager = BleManager.init();
        bleManager.initialize();
        setBluetoothPopwind();
        mSoundCard = new SoundCard(1, mPlayFre, mSampleFre);
        audiomanage = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_baby_voice;
    }

    @Override
    protected void onResume() {
        super.onResume();
        Boolean isConn = (Boolean) SharedPreferencesUtils.getParam("Voice", false);//通过share保存蓝牙连接状态
        if (isConn) {
            hintTv.setText("已连接");
        } else {
            hintTv.setText("未连接");
        }
        registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());

        switchButton.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton switchButton, boolean isOpen) {
             if (!isOpen){
                 audiomanage.setStreamVolume(AudioManager.STREAM_RING,0,0);
             }else {
                 audiomanage.setStreamVolume(AudioManager.STREAM_RING,60,0);
             }
            }
        });

    }
    List<Float> YData=new ArrayList<>();
    private void setLineChart() {

        List<Entry> entries = new ArrayList<Entry>();

        for (int i=0;i<YData.size();i++){
            entries.add(new Entry(i,YData.get(i)));
        }

        LineDataSet dataSet = new LineDataSet(entries, "胎心率"); // add entries to dataset
        dataSet.setColor(Color.RED);
        dataSet.setCircleColor(Color.RED);
        dataSet.setDrawValues(false);
        LineData lineData = new LineData(dataSet);
        voiceChart.getDescription().setEnabled(false);//设置图表描
        voiceChart.setData(lineData);
        voiceChart.invalidate(); // refresh
        // turn your data into Entry objects
        //获取右边的轴线
        YAxis rightAxis=voiceChart.getAxisRight();
        //设置图表右边的y轴禁用
        rightAxis.setEnabled(false);
        XAxis xAxis = voiceChart.getXAxis();
        xAxis.setEnabled(true);//设置轴启用或禁用 如果禁用以下的设置全部不生效
        xAxis.setDrawAxisLine(true);//是否绘制轴线
        xAxis.setDrawGridLines(true);//设置x轴上每个点对应的线
        xAxis.setDrawLabels(true);//绘制标签  指x轴上的对应数值
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);//设置x轴的显示位置
//        thermometerChart.setData(lineData);
    }
    private static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BleManager.ACTION_GATT_CONNECTED);
        intentFilter.addAction(BleManager.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(BleManager.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(BleManager.ACTION_DATA_AVAILABLE);
        return intentFilter;
    }

    /*广播回调*/
    int len;
    int i;
    int j;
    int temp;
    int count;
    private final int mRevDataBufMaxLen = 200;
    byte mRevDataBuf[] = new byte[mRevDataBufMaxLen];
    int mRevDataLength = 0;
    static final int mSampleFre = 2000;
    static final int mPlayFre = 8000;
    StringBuilder stringBuilder=new StringBuilder();
    short [] outdata=new short[200];
    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (BleManager.ACTION_GATT_CONNECTED.equals(action)) {
                Log.e("MLOG", "ACTION_GATT_CONNECTED");
            } else if (BleManager.ACTION_GATT_DISCONNECTED.equals(action)) { //蓝牙断开连接
                Log.e("MLOG", "ACTION_GATT_DISCONNECTED");
                SharedPreferencesUtils.setParam("Voice", false);
                hintTv.setText("未连接");
            } else if (BleManager.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {  //蓝牙连接成功
                // Show all the supported services and characteristics on the user interface.
                Log.e("MLOG", ">>>>>>>>>>>");
                List<BluetoothGattService> supportedGattServices = bleManager.getSupportedGattServices();
                showList(supportedGattServices);
                infoBluetooth();
                bleManager.initNotify(StarConstants.BABY_VOICE_SERVICE_ID, StarConstants.BABY_VOICE_READ_ID, StarConstants.BABY_VOICE_WEITE_ID);
            } else if (BleManager.ACTION_DATA_AVAILABLE.equals(action)) {  //蓝牙数据返回
                if (intent.getStringExtra(BleManager.EXTRA_DATA) != null) {
                    String codeVoice = intent.getStringExtra(BleManager.EXTRA_DATA);
                    Log.e("MLOG", codeVoice);
                    String[] voiceSplit = codeVoice.split(" ");
                    if (TextUtils.equals(voiceSplit[0],"FF")&&TextUtils.equals(voiceSplit[1],"AA")) {
                        if (stringBuilder.length()!=0) {
                            stringBuilder.delete(0,stringBuilder.length()-1);
                        }
                    }
                    stringBuilder.append(codeVoice);
                    Log.e("MLOG",">>>>>>>>>>>"+stringBuilder.length());
                    if (stringBuilder.length()==175) {
                        String replace = stringBuilder.toString().replace(" ", "");
                        Log.e("MLOG",replace);
                        count=  FetalHeartRate.processInComingFrameData(ByteToStringUtils.hexStringToByteArray(replace),outdata);
                        if (count!=-1) {
                            voiceTv.setText(count+"bpm");
                            mSoundCard.WriteData(outdata, 100);
                            YData.add((float) count);
                            setLineChart();
                        }else {

                        }
                    }





                }
            }
        }
    };


        /*获取蓝牙服务列表*/
        List<BluetoothGattCharacteristic> mBluetoothList = new ArrayList<>();

        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
        public void showList(List<BluetoothGattService> gattServices) {
            for (BluetoothGattService gattService : gattServices) {
                List<BluetoothGattCharacteristic> gattCharacteristics =
                        gattService.getCharacteristics();
                for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
                    mBluetoothList.add(gattCharacteristic);
                }
            }
        }

    /*设置蓝牙服务可读可写*/

        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
        public void infoBluetooth() {
            for (BluetoothGattCharacteristic characteristic : mBluetoothList) {
                bleManager.setCharacteristicNotification(
                        characteristic, false);
            }

        }

        @OnClick({R.id.back, R.id.hint_tv, R.id.item_play})
        public void onViewClicked(View view) {
            switch (view.getId()) {
                case R.id.back:
                    AppManager.getAppManager().finishActivity();
                    break;
                case R.id.hint_tv:
                    if (hintTv.getText().equals("未连接")) {
                        PopWindowManager.showAsLocationWindow(praentView, blueContentView, bluePopupWindow, R.id.bluetooth_popwind_layout);
                    }
                    break;
                case R.id.item_play://播放声音
                 File file = new File(WavFileOpration.mTempFileName);
                    if (file != null) {
                        MediaPlayerManager.playSound(file.getPath(), new MediaPlayer.OnCompletionListener() {
                            @Override
                            public void onCompletion(MediaPlayer mp) {

                            }
                        });
                    }
                    break;
            }
        }

        private PopupWindow bluePopupWindow;
        private View blueContentView;
        private View praentView;

        //设置弹窗
        private void setBluetoothPopwind() {
            praentView = LayoutInflater.from(this).inflate(R.layout.activity_msg_list, null);
            blueContentView = LayoutInflater.from(this).inflate(R.layout.bluetooth_popwind_layout, null);
            bluePopupWindow = new PopupWindow(blueContentView,
                    LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, true);

            Button cancelBut = (Button) blueContentView.findViewById(R.id.cancel_but);
            Button commentBut = (Button) blueContentView.findViewById(R.id.setting_but);

            //点击事件
            setEvent(cancelBut, commentBut, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    switch (v.getId()) {
                        case R.id.cancel_but: //取消
                            bluePopupWindow.dismiss();
                            break;
                        case R.id.setting_but:  //设置
                            bluePopupWindow.dismiss();
                            startActivity(new Intent(BabyVoiceActivity.this, BluetoothListActivity.class));
                            break;
                    }

                }
            });
        }

        //设置点击事件
        private void setEvent(Button cancelBut, Button commentBut, View.OnClickListener listener) {
            cancelBut.setOnClickListener(listener);
            commentBut.setOnClickListener(listener);
        }

        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
        @Override
        protected void onDestroy() {
            super.onDestroy();
            if (bleManager != null) {
                bleManager.disableBlueBle("Voice");
            }
            if (mGattUpdateReceiver != null) {
                unregisterReceiver(mGattUpdateReceiver);
            }
        }



}